<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%@ include file="/common/user.jsp"%>
<%
    Integer uid = token.getUid();
    List<UserProfile> userProfiles = QBuilder.db("basedb").select().from("UserProfile").where(new Where("hospital=", hospital).and("status = ", STATUS_ENABLE).and("uid=", uid)).query().getResultObj();
    if (userProfiles.size() > 5) {
        Tools.encryptPrint(out, new Message(30091, "不能添加超过5个就诊人"));
        return;
    }
    UserProfile userProfile = UserProfile.fromMap(parameters, UserProfile.class);
    String name = userProfile.getName();
    String phone = userProfile.getPhone();
	if (!isChinaPhoneLegal(phone)) {
		Tools.encryptPrint(out, new Message(30000, "手机号不合法"));
        return;
	}
	if (!isChinaNameLegal(name)) {
		Tools.encryptPrint(out, new Message(30000, "姓名为2-20位中文或字符"));
        return;
	}
    userProfile.setCardNumber(userProfile.getCardNumber().toUpperCase());
    String cardNumber = userProfile.getCardNumber();
    if ("身份证".equals(Tools.getDesc(userProfile.getCardType(), "身份证"))) {
		if (cardNumber == null || "".equals(cardNumber)) {
			Tools.encryptPrint(out, new Message(30028, "身份证不能为空"));
        	return;
		}
    	// 校验身份证号码合法性
        cardNumber = fixPersonIDCode(userProfile.getCardNumber());
        if(!IdCardUtil.validateIdCard18(cardNumber)){
            Tools.encryptPrint(out, new Message(30028, "身份证不正确"));
        	return;
        }
        userProfile.setCardType("身份证");
        userProfile.setGender((IdCardUtil.getGender(cardNumber))%2);
        userProfile.setBirthday(IdCardUtil.getBirth(cardNumber));
        userProfile.setAge(IdCardUtil.getAgeByIdCard(cardNumber));
    }
    for (UserProfile up : userProfiles) {
        if (cardNumber.equalsIgnoreCase(up.getCardNumber())) {
            Tools.encryptPrint(out, new Message(30090, "该就诊人信息已存在"));
            return;
        }
    }
    userProfile.setSelf(FAMILY);
    userProfile.setUid(token.getUid());
    Integer id = (Integer)DBTools.db("basedb").addItem(userProfile);
    if (isEmpty(id)) {
        Tools.encryptPrint(out, new Message(30000, "就诊人添加失败"));
        return;
    }
    List<Map> family = family(uid, hospital);
    if (isEmpty(family)) {
        msg = new Message(30041, "暂未添加就诊人");
    }
    msg.put("data", family);
    Tools.encryptPrint(out, msg);
%>
